package com.btr.ivle.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;


public class DataSourceAnnouncement {
	
	private SQLiteDatabase db;
	private DatabaseAnnouncement dbHelper;
	
	public final String TABLE_SUFFIX = "_ANNOUNCEMENT";
	public final String AnnouncementID="AnnouncementID";
	public final String CourseCode="AnnouncementCourseCode";
	public final String Title="AnnouncementTitle";
	public final String Description ="AnnouncementDescription";
	public final String CreatedDate="AnnouncementCreatedDate";
	public final String CreatorName="AnnouncementCreatorName";
	public final String isRead="AnnouncementIsRead";
	
	public DataSourceAnnouncement(Context context){
		dbHelper = new DatabaseAnnouncement(context, IVLEToken.getUserID()+TABLE_SUFFIX, null, context.getResources().getInteger(R.integer.DBVersion));
	}
	
	public void open() throws SQLException {
		db = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public Cursor getAnnouncementByID(String ID){
		
		String[] columns = new String[] {dbHelper.Title, dbHelper.Description, 
				dbHelper.CreatedDate, dbHelper.CreatorName};
        String selection = dbHelper.AnnouncementID + "=?";
		String[] selectionArgs = new  String[] {ID};
		
		Cursor cursor = db.query(dbHelper.tableName, columns, 
        		selection, selectionArgs, null, null, null, null);

        cursor.moveToFirst();
		
		return cursor;
	}

	public Cursor getAnnouncementsByCourseCode(String courseCode) {
		
        String[] columns = new String[] {dbHelper.AnnouncementID, dbHelper.Title,
        		dbHelper.Description, dbHelper.CreatedDate};
        String selection = dbHelper.CourseCode + "=?";
		String[] selectionArgs = new  String[] {courseCode};
        String orderBy = dbHelper.CreatedDate + " DESC";
        
        Cursor cursor = db.query(dbHelper.tableName, columns, 
        		selection, selectionArgs, null, null, orderBy, null);
        cursor.moveToFirst();
        
		return cursor;
	}

	public void updateEntry(ContentValues values) {
		db.replace(dbHelper.tableName, null, values);
		db.insertWithOnConflict(dbHelper.tableName, null, values, SQLiteDatabase.CONFLICT_IGNORE);
	}
	
}
